import axios from "axios";
import qs from "qs";
import router from "@/router";
import { Toast } from "vant";

// https://www.haixisz.com
let api = "";
let isCancel;
let CancelRequest;

const Axios = axios.create({
  timeout: 1000 * 10,


  cancelToken: new axios.CancelToken((ct) => {
    isCancel = false;
    CancelRequest = ct;
  }),
});
// 请求拦截器
Axios.interceptors.request.use(
  (config) => {
    let arr = config.url.split("/");
    if (arr[arr.length - 2] == "file" && arr[arr.length - 1] == "upload") {
      config.timeout = 1000 * 60 * 10;
    }
    let time = parseInt(new Date().getTime() / 1000) + "";
    console.log(time);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
Axios.interceptors.response.use(
  (res) => {
    if (res.status === 200) {
      switch (res.data.code) {
        case 0:
          break;
        case 10002:
          toLogin();
          break;
        default:
          // Toast(res.data.message);

          break;
      }
      return Promise.resolve(res);
    } else {
        Toast("服务器错误");
    }
    // return response;
  },
  (error) => {
    Toast("网络请求超时");
    return Promise.reject(error);
  }
);

const get = (url, params) => {
  return new Promise((resolve, reject) => {
    Axios.get(api + url, {
      params: params,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
};

const post = (url, params) => {
  return new Promise((resolve, reject) => {
    let data = params;
    if (url != "/file/upload") {
      qs.stringify(params);
    }
    Axios.post(api + url, data)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
};

const toLogin = () => {
  router.replace({
    path: "/?" /* + new Date().getTime() */,
  });
};

const cancel = () => {
  //取消请求
  isCancel = true;
  CancelRequest();
};
export default {
  get,
  post,
  cancel,
};
